#include "loginform.h"

#include <QHBoxLayout>
#include <QHeaderView>
#include <QSqlRecord>
#include <QCryptographicHash>
#include <QMessageBox>
#include <QKeyEvent>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>


#include "../settings.h"
#include "../service.h"
#include "../definitions.h"
#include "../components/numpad.h"

LoginForm::LoginForm(QWidget *parent) :
    FormInterface(parent)
{
    QHBoxLayout *mainLayout = new QHBoxLayout(this);

    QSqlQuery que;

    QSettings *settings = Settings::getInstance();

    loglevel = Settings::getVariables()->value("loglevel").toInt();

    que.prepare(settings->value("queries/login/get_userslist").toString());
    que.bindValue(":pos", Settings::getDefinition("ТЕКУЩАЯ_БАЗА").toInt());

    if(!que.exec()){
        qCritical()<<(loglevel>1?posInFile:"")<<endl
                        <<"Ошибка :"<<endl
                        <<que.lastError().text()<<endl
                        <<"Запрос: "<<que.lastQuery()<<endl
                        <<"Переменные: "<<que.boundValues();

        QMessageBox message;
        message.setText("Ошибка получения списка пользователей\nТекст: \n"+que.lastError().text());
        message.exec();

        return;
    }

    model = new QSqlQueryModel(this);
    model->setQuery(que);
    model->setHeaderData(0, Qt::Horizontal, "Пользователи");

    view = new QTableView(this);
    view->setModel(model);

    view->setSelectionMode(QAbstractItemView::SingleSelection);


    view->hideColumn(1);
    view->hideColumn(2);

    QHeaderView *header = view->verticalHeader();
    header->setDefaultSectionSize(settings->value("globals/table_height").toInt());
    header->setVisible(false);

    header = view->horizontalHeader();
    header->setStretchLastSection(true);

    view->setFocusPolicy(Qt::NoFocus);

    mainLayout->addWidget(view);

    QVBoxLayout *numpadLayout = new QVBoxLayout();

    Numpad *npad = new Numpad(this);
    npad->setEchoMode(QLineEdit::Password);

    numpadLayout->addWidget(npad);
    numpadLayout->addStretch(1);

    mainLayout->addLayout(numpadLayout);

    connect(npad, SIGNAL(inputCommited(QString)),
               this, SLOT(passwordCommited(QString)));

    setFocusProxy(npad);

    this->installEventFilter(this);

    QMap<QString,QVariant> *var = Settings::getVariables();
    var->remove("user");
    var->remove("user_id");
}

LoginForm::~LoginForm()
{

}

void LoginForm::passwordCommited(const QString &text){
    int row = view->currentIndex().row();
    if(row==-1){
        if(loglevel > 2)
         qWarning()<<(loglevel>1?posInFile:"")<<"Ошибка входа. Не выбран пользователь";

        QMessageBox *message = new QMessageBox(this);
        message->setText("Не выбран пользователь");
        message->exec();
        return;
    }
    QSqlRecord record = model->record(row);
    QString pass = record.value(2).toString();


 //   QCryptographicHash *hash = new QCryptographicHash(QCryptographicHash::Md5);
 //   hash->addData(text.toLatin1());
 //   if (hash->result().toHex()!=pass){
      if (text.toLatin1()!=pass){
        if(loglevel > 2)
         qWarning()<<(loglevel>1?posInFile:"")<<"Ошибка входа. Пользователь "<<record.value(0).toString()<<" пароль:  "<<text.toLatin1();

        QMessageBox *message = new QMessageBox(this);
        message->setText("Неверный пароль или имя пользователя");
        message->exec();
    }else {
        QMap<QString,QVariant> *var = Settings::getVariables();
        var->insert("user", record.value(0));
        var->insert("user_id", record.value(1));

        if(loglevel > 0)
         qDebug()<<(loglevel>1?posInFile:"")<<"Вход. Пользователь "<<record.value(0).toString()<<" пароль:  "<<text.toLatin1();

        emit loggedIn();
    }

}


bool LoginForm::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key()==Qt::Key_Down){
            int row = view->currentIndex().row();
            QModelIndex idx = view->currentIndex().sibling(row+1,0);
            if(idx.isValid())
              view->setCurrentIndex(idx);
            else{
                QModelIndex idx = view->indexAt(QPoint(0,0));
                if(idx.isValid())
                  view->setCurrentIndex(idx);
            }
            return true;
        }
        if(keyEvent->key()==Qt::Key_Up){
            int row = view->currentIndex().row();
            QModelIndex idx = view->currentIndex().sibling(row-1,0);
            if(idx.isValid())
              view->setCurrentIndex(idx);
            return true;
        }
    }

    return QWidget::eventFilter(obj, event);
}
